import logging
import pandas as pd
import numpy as np
import matplotlib

matplotlib.use('Qt5Agg')
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel,
                             QComboBox, QFrame, QSizePolicy, QMessageBox,
                             QTableWidget, QTableWidgetItem, QHeaderView)
from PyQt5.QtGui import QFont, QColor
from PyQt5.QtCore import Qt
from datetime import datetime, timedelta
import matplotlib.pyplot as plt

# 设置Matplotlib中文字体支持
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'Arial Unicode MS']
plt.rcParams['axes.unicode_minus'] = False

# 全局样式变量
PRIMARY_COLOR = "#3498db"  # 主题蓝色
SECONDARY_COLOR = "#2ecc71"  # 绿色
WARNING_COLOR = "#e74c3c"  # 警告红色
BG_COLOR = "#f8f9fa"  # 背景色
TEXT_COLOR = "#2c3e50"  # 文字颜色
GREEN_BG_COLOR = "#e8f5e9"  # 绿色背景色
BLUE_BG_COLOR = "#e3f2fd"  # 蓝色背景色
PURPLE_COLOR = "#9b59b6"  # 紫色用于变化值
ACCENT_COLOR = "#34495e"  # 深色用于标签

# 饼图颜色方案
INCOME_COLORS = ['#4CAF50', '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107']
EXPENSE_COLORS = ['#F44336', '#E91E63', '#9C27B0', '#673AB7', '#3F51B5']

# 字体配置
HEADER_FONT = QFont("Microsoft YaHei UI", 12, QFont.Bold)
LABEL_FONT = QFont("Microsoft YaHei UI", 10)
BUTTON_FONT = QFont("Microsoft YaHei UI", 10, QFont.Bold)
INPUT_FONT = QFont("Microsoft YaHei UI", 10)
VALUE_FONT = QFont("Microsoft YaHei UI", 11, QFont.Bold)  # 数值字体加粗


class IncomeExpenseAnalysisTab(QWidget):
    def __init__(self, db, card_id):
        super().__init__()
        self.db = db
        self.card_id = card_id
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)
        self.initUI()
        self.apply_styles()
        self.load_data()

    def initUI(self):
        # 主布局
        main_layout = QVBoxLayout(self)
        main_layout.setSpacing(15)
        main_layout.setContentsMargins(20, 15, 20, 20)

        # ================= 月份选择 =================
        month_layout = QHBoxLayout()
        month_layout.setContentsMargins(0, 0, 0, 10)

        # 月份选择
        month_label = QLabel("选择月份:")
        month_label.setFont(LABEL_FONT)
        month_layout.addWidget(month_label)

        self.month_combo = QComboBox()
        self.month_combo.setFont(INPUT_FONT)
        self.month_combo.setMinimumWidth(150)
        self.populate_months()
        self.month_combo.currentIndexChanged.connect(self.month_changed)
        month_layout.addWidget(self.month_combo)

        month_layout.addStretch(1)
        main_layout.addLayout(month_layout)

        # ================= 收支概览 =================
        overview_layout = QHBoxLayout()
        overview_layout.setSpacing(15)

        # 收入框
        self.income_frame = self.create_info_frame("总收入", "¥0.00", SECONDARY_COLOR, GREEN_BG_COLOR)
        overview_layout.addWidget(self.income_frame)

        # 支出框
        self.expense_frame = self.create_info_frame("总支出", "¥0.00", WARNING_COLOR, "#fce4ec")
        overview_layout.addWidget(self.expense_frame)

        # 净收入框
        self.net_frame = self.create_info_frame("净收入", "¥0.00", PRIMARY_COLOR, BLUE_BG_COLOR)
        overview_layout.addWidget(self.net_frame)

        # 较上月框
        self.change_frame = self.create_info_frame("较上月", "¥0.00", PURPLE_COLOR, "#f3e5f5")
        overview_layout.addWidget(self.change_frame)

        main_layout.addLayout(overview_layout)

        # ================= 图表区域 =================
        chart_layout = QVBoxLayout()
        chart_layout.setSpacing(5)

        # 标签
        chart_label = QLabel("月度收支趋势")
        chart_label.setFont(HEADER_FONT)
        chart_layout.addWidget(chart_label)

        # 折线图容器
        self.chart_frame = QFrame()
        self.chart_frame.setObjectName("chartFrame")
        self.chart_frame.setStyleSheet("background-color: white; border-radius: 8px;")
        self.chart_frame.setMinimumHeight(320)
        self.chart_frame.setLayout(QVBoxLayout())
        self.chart_frame.layout().setContentsMargins(5, 5, 5, 5)

        # 初始空图表
        self.create_empty_chart()

        chart_layout.addWidget(self.chart_frame)
        main_layout.addLayout(chart_layout)

        # ================= 交易类型统计 =================
        type_layout = QVBoxLayout()
        type_layout.setSpacing(5)

        # 标签
        type_label = QLabel("交易类型统计")
        type_label.setFont(HEADER_FONT)
        type_layout.addWidget(type_label)

        # 创建水平布局用于饼图和表格
        type_content_layout = QHBoxLayout()

        # 饼图容器（左侧）- 增加比例到55%
        pie_frame = QFrame()
        pie_frame.setObjectName("pieFrame")
        pie_frame.setStyleSheet("background-color: white; border-radius: 8px;")
        pie_layout = QVBoxLayout(pie_frame)
        pie_layout.setContentsMargins(10, 10, 10, 10)

        # 收入饼图容器
        self.income_pie_container = QFrame()
        self.income_pie_container.setLayout(QVBoxLayout())
        self.income_pie_container.layout().setContentsMargins(0, 0, 0, 0)
        pie_layout.addWidget(QLabel("收入分类"))
        pie_layout.addWidget(self.income_pie_container)

        # 支出饼图容器
        self.expense_pie_container = QFrame()
        self.expense_pie_container.setLayout(QVBoxLayout())
        self.expense_pie_container.layout().setContentsMargins(0, 0, 0, 0)
        pie_layout.addWidget(QLabel("支出分类"))
        pie_layout.addWidget(self.expense_pie_container)

        type_content_layout.addWidget(pie_frame, 55)  # 增加到55%宽度

        # 交易类型表格（右侧）- 减少到45%
        self.type_table = QTableWidget()
        self.type_table.setObjectName("typeTable")
        self.type_table.setColumnCount(2)
        self.type_table.setHorizontalHeaderLabels(["交易类型", "金额"])
        self.type_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.type_table.verticalHeader().setVisible(False)
        self.type_table.setEditTriggers(QTableWidget.NoEditTriggers)
        self.type_table.setMinimumHeight(250)

        type_content_layout.addWidget(self.type_table, 45)  # 减少到45%宽度

        type_layout.addLayout(type_content_layout)
        main_layout.addLayout(type_layout)

        # ================= 银行卡统计 =================
        card_layout = QVBoxLayout()
        card_layout.setSpacing(5)

        # 标签
        card_label = QLabel("银行卡收支统计")
        card_label.setFont(HEADER_FONT)
        card_layout.addWidget(card_label)

        # 银行卡表格 - 设置高度策略为Expanding以占满空间
        self.card_table = QTableWidget()
        self.card_table.setObjectName("cardTable")
        self.card_table.setColumnCount(4)
        self.card_table.setHorizontalHeaderLabels(["卡号", "收入", "支出", "净收入"])
        self.card_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.card_table.verticalHeader().setVisible(False)
        self.card_table.setEditTriggers(QTableWidget.NoEditTriggers)
        self.card_table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        card_layout.addWidget(self.card_table, 1)  # 添加拉伸因子1以占满空间
        main_layout.addLayout(card_layout, 1)  # 添加拉伸因子1以占满空间

    def create_info_frame(self, title, value, color, bg_color):
        """创建信息卡片"""
        frame = QFrame()
        frame.setObjectName(f"{title.replace(' ', '')}Frame")
        layout = QVBoxLayout(frame)
        layout.setContentsMargins(10, 10, 10, 10)
        layout.setSpacing(8)

        # 标题
        title_label = QLabel(title)
        title_label.setFont(LABEL_FONT)
        title_label.setAlignment(Qt.AlignCenter)
        title_label.setStyleSheet(f"color: {color}; font-weight: bold;")
        layout.addWidget(title_label)

        # 数值
        value_label = QLabel(value)
        value_label.setFont(VALUE_FONT)
        value_label.setAlignment(Qt.AlignCenter)
        value_label.setStyleSheet(f"color: {color};")

        # 保存引用
        if title == "总收入":
            self.income_value = value_label
        elif title == "总支出":
            self.expense_value = value_label
        elif title == "净收入":
            self.net_value = value_label
        elif title == "较上月":
            self.change_value = value_label

        layout.addWidget(value_label)

        frame.setStyleSheet(f"""
            #{title.replace(' ', '')}Frame {{
                background-color: {bg_color};
                border: 1px solid {color};
                border-radius: 8px;
            }}
        """)

        return frame

    def apply_styles(self):
        """应用样式表"""
        self.setStyleSheet(f"""
            QWidget {{
                background-color: {BG_COLOR};
                color: {TEXT_COLOR};
            }}

            QComboBox {{
                background-color: white;
                border: 1px solid #e0e0e0;
                border-radius: 4px;
                padding: 8px 12px;
                min-height: 30px;
                font-size: 11pt;
            }}

            QLabel {{
                font: {LABEL_FONT};
            }}

            QTableWidget {{
                background-color: white;
                border-radius: 8px;
            }}

            QHeaderView::section {{
                background-color: {PRIMARY_COLOR};
                color: white;
                font-weight: bold;
                padding: 8px;
                border: none;
            }}

            #pieFrame {{
                background-color: white;
                border-radius: 8px;
            }}
        """)

    def populate_months(self):
        """填充月份选项"""
        current_month = datetime.now().replace(day=1)

        # 添加最近6个月
        for i in range(5, -1, -1):
            month_date = current_month - timedelta(days=30 * i)
            month_str = month_date.strftime("%Y-%m")
            self.month_combo.addItem(f"{month_date.year}年{month_date.month:02d}月", month_str)

        # 设置当前月为默认选择
        self.month_combo.setCurrentIndex(self.month_combo.count() - 1)

    def month_changed(self, index):
        """月份选择变更处理"""
        if index >= 0:
            self.load_data()

    def load_data(self):
        """加载分析数据 """
        month_str = self.month_combo.currentData()

        try:
            # 1. 使用日期范围查询
            start_date = month_str + "-01"
            end_date = (datetime.strptime(month_str, "%Y-%m") + timedelta(days=31)).strftime("%Y-%m-%d")

            # 2. 查询当前月份数据
            query_current = """
            SELECT 
                tradeID, cardID, tradeDate, tradeType, tradeMoney, targetCard, remark 
            FROM tradeinfo 
            WHERE cardID = %s
            AND tradeDate BETWEEN %s AND %s
            """
            results_current = self.db.execute_query(query_current, (self.card_id, start_date, end_date))

            # 3. 确保查询结果正确转换
            columns = ['tradeID', 'cardID', 'tradeDate', 'tradeType', 'tradeMoney', 'targetCard', 'remark']
            df = pd.DataFrame(results_current, columns=columns) if results_current else pd.DataFrame()

            # 如果没有交易记录，重置UI并返回
            if df.empty:
                self.logger.info(f"本月无交易记录")
                self.reset_ui()
                return

            # 4. 确保数据正确解析
            try:
                # 将tradeMoney转换为数值类型
                df['tradeMoney'] = pd.to_numeric(df['tradeMoney'], errors='coerce')
                # 确保tradeDate是datetime类型
                df['tradeDate'] = pd.to_datetime(df['tradeDate'], errors='coerce')
                # 移除无效数据
                df.dropna(subset=['tradeMoney', 'tradeDate'], inplace=True)
            except Exception as e:
                self.logger.error(f"数据处理错误: {str(e)}")
                raise

            # 5. 计算收入和支出
            total_income = df[df['tradeMoney'] > 0]['tradeMoney'].sum() or 0
            total_expense = abs(df[df['tradeMoney'] < 0]['tradeMoney'].sum()) or 0
            net_income = total_income - total_expense

            # 6. 更新UI显示
            self.income_value.setText(f"¥{float(total_income):,.2f}")
            self.expense_value.setText(f"¥{float(total_expense):,.2f}")
            self.net_value.setText(f"¥{float(net_income):,.2f}")

            # 7. 按交易类型统计金额
            try:
                # 定义交易类型计算函数
                def calc_amount(group):
                    if group.name == '存入':
                        return group[group > 0].sum()
                    elif group.name == '转账入':
                        return group[group > 0].sum()
                    elif group.name == '转账出':
                        return abs(group[group < 0].sum())
                    elif group.name == '支取':
                        return abs(group[group < 0].sum())
                    elif group.name == '消费支出':
                        return abs(group[group < 0].sum())
                    elif group.name == '利息收入':
                        return group[group > 0].sum()
                    else:  # 其他类型
                        return group.abs().sum()

                # 按交易类型分组并计算金额
                type_amounts = df.groupby('tradeType')['tradeMoney'].agg(amount=calc_amount).reset_index()

                # 删除金额为0的记录
                type_amounts = type_amounts[type_amounts['amount'] != 0]

                self.update_type_table(type_amounts)
            except Exception as e:
                self.logger.error(f"交易类型统计错误: {str(e)}")

            # 8. 按银行卡号统计收支
            try:
                card_amounts = df.groupby('cardID').agg(
                    income=('tradeMoney', lambda x: x[x > 0].sum()),
                    expense=('tradeMoney', lambda x: abs(x[x < 0].sum())),
                    net_income=('tradeMoney', lambda x: x[x > 0].sum() - abs(x[x < 0].sum()))
                ).reset_index()
                self.update_card_table(card_amounts)
            except Exception as e:
                self.logger.error(f"银行卡统计错误: {str(e)}")

            # 9. 生成每日数据
            try:
                daily_df = df.copy()
                daily_df['tradeDate'] = daily_df['tradeDate'].dt.date

                # 创建完整日期范围
                selected_month = datetime.strptime(month_str, "%Y-%m")
                start_date = selected_month.replace(day=1)
                end_date = (selected_month.replace(day=28) + timedelta(days=4)).replace(day=1) - timedelta(days=1)
                date_range = pd.date_range(start=start_date, end=end_date, freq='D')

                # 按日汇总收入
                income_daily = daily_df[daily_df['tradeMoney'] > 0].groupby('tradeDate')['tradeMoney'].sum().reindex(
                    date_range.date, fill_value=0)
                # 按日汇总支出
                expense_daily = daily_df[daily_df['tradeMoney'] < 0].groupby('tradeDate')['tradeMoney'].sum().reindex(
                    date_range.date, fill_value=0)
                # 计算每日净收入
                net_daily = income_daily + expense_daily


                if not isinstance(net_daily.index, pd.DatetimeIndex):
                    net_daily.index = pd.to_datetime(net_daily.index)

                # 生成图表
                self.generate_chart(income_daily, expense_daily, net_daily)
            except Exception as e:
                self.logger.error(f"生成每日数据错误: {str(e)}")
                self.create_empty_chart()

        except Exception as e:
            self.logger.error(f"加载数据错误: {str(e)}")
            self.reset_ui()
            QMessageBox.critical(self, "数据错误",
                                 f"加载数据时发生错误:\n{str(e)}")

    def reset_ui(self):
        """重置UI为初始状态"""
        self.income_value.setText("¥0.00")
        self.expense_value.setText("¥0.00")
        self.net_value.setText("¥0.00")
        self.change_value.setText("¥0.00")
        self.change_value.setStyleSheet("")

        # 清空表格
        self.type_table.setRowCount(0)
        self.card_table.setRowCount(0)

        # 创建空图表占位
        self.create_empty_chart()

        # 清除饼图
        self.clear_pie_charts()

    def create_empty_chart(self):
        """创建空图表占位 - 安全方法"""
        # 清除现有图表
        layout = self.chart_frame.layout()
        while layout.count():
            widget = layout.takeAt(0).widget()
            if widget: widget.deleteLater()

        # 创建新的空图表
        fig = Figure(figsize=(8, 4), dpi=100)
        ax = fig.add_subplot(111)
        ax.text(0.5, 0.5, "无数据可用",
                ha='center', va='center', fontsize=12)
        ax.set_title("月度收支趋势", fontsize=12)
        ax.axis('off')  # 隐藏坐标轴

        canvas = FigureCanvas(fig)
        layout.addWidget(canvas)

    def clear_pie_charts(self):
        """清除饼图容器内容"""
        # 清除收入饼图
        layout_income = self.income_pie_container.layout()
        while layout_income.count():
            widget = layout_income.takeAt(0).widget()
            if widget: widget.deleteLater()

        # 清除支出饼图
        layout_expense = self.expense_pie_container.layout()
        while layout_expense.count():
            widget = layout_expense.takeAt(0).widget()
            if widget: widget.deleteLater()

        # 添加占位文本
        # no_data_label_income = QLabel("收入分类\n无数据")
        # no_data_label_income.setAlignment(Qt.AlignCenter)
        # no_data_label_income.setStyleSheet("color: #999999; font-size: 10pt;")
        # self.income_pie_container.layout().addWidget(no_data_label_income)
        #
        # no_data_label_expense = QLabel("支出分类\n无数据")
        # no_data_label_expense.setAlignment(Qt.AlignCenter)
        # no_data_label_expense.setStyleSheet("color: #999999; font-size: 10pt;")
        # self.expense_pie_container.layout().addWidget(no_data_label_expense)

    def update_type_table(self, type_amounts):
        """更新交易类型表格和饼状图"""
        # 更新表格
        self.type_table.setRowCount(len(type_amounts))

        for row_idx, row in type_amounts.iterrows():
            # 交易类型
            type_item = QTableWidgetItem(row['tradeType'])
            type_item.setTextAlignment(Qt.AlignCenter)
            self.type_table.setItem(row_idx, 0, type_item)

            # 金额
            amount = row['amount']
            amount_item = QTableWidgetItem(f"¥{amount:,.2f}")
            amount_item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)

            # 设置颜色
            if row['tradeType'] in ['存入', '转账入']:
                amount_item.setForeground(QColor(SECONDARY_COLOR))
            else:
                amount_item.setForeground(QColor(WARNING_COLOR))

            self.type_table.setItem(row_idx, 1, amount_item)

        # 生成饼图
        self.generate_pie_charts(type_amounts)

    def generate_pie_charts(self, type_amounts):
        """生成收入和支出饼状图"""
        # 分离收入和支出数据
        income_types = ['存入', '转账入', '利息收入', '工资收入', '奖金入账']
        expense_types = ['转账出', '支取', '消费支出', '转账费用', '手续费']

        # 正确分离收入和支出数据
        income_data = type_amounts[type_amounts['tradeType'].isin(income_types)]
        expense_data = type_amounts[type_amounts['tradeType'].isin(expense_types)]
        # 清除饼图容器
        self.clear_pie_charts()

        # 生成收入饼图
        if not income_data.empty:
            self.create_pie_chart(
                income_data,
                "收入分类",
                self.income_pie_container,
                INCOME_COLORS
            )
        else:
            no_data_label = QLabel("收入分类\n无数据")
            no_data_label.setAlignment(Qt.AlignCenter)
            no_data_label.setStyleSheet("color: #999999; font-size: 10pt;")
            self.income_pie_container.layout().addWidget(no_data_label)

        # 生成支出饼图
        if not expense_data.empty:
            self.create_pie_chart(
                expense_data,
                "支出分类",
                self.expense_pie_container,
                EXPENSE_COLORS
            )
        else:
            no_data_label = QLabel("支出分类\n无数据")
            no_data_label.setAlignment(Qt.AlignCenter)
            no_data_label.setStyleSheet("color: #999999; font-size: 10pt;")
            self.expense_pie_container.layout().addWidget(no_data_label)

    def create_pie_chart(self, data, title, container, colors):
        """创建饼状图 - 放大尺寸"""
        # 创建图表 - 放大饼图尺寸
        fig = Figure(figsize=(10, 10), dpi=100)  # 从(3,3)放大到(5,5)
        ax = fig.add_subplot(111)

        # 提取标签和数值
        labels = data['tradeType'].tolist()
        sizes = data['amount'].tolist()

        # 生成饼图
        wedges, texts, autotexts = ax.pie(
            sizes,
            labels=labels,
            autopct=lambda p: f'{p:.1f}%\n¥{p * sum(sizes) / 100:,.0f}',
            startangle=90,
            colors=colors[:len(labels)],
            wedgeprops={'edgecolor': 'white', 'linewidth': 0.5},
            textprops={'fontsize': 10}  # 增大字体大小
        )

        # 设置标题
        ax.set_title(title, fontsize=12)  # 增大标题字体

        # 添加总金额标签
        total = sum(sizes)
        fig.text(0.5, 0.05, f"总金额: ¥{total:,.2f}",
                 ha='center', fontsize=11, color=ACCENT_COLOR)  # 增大字体

        # 将图表嵌入到PyQt中
        canvas = FigureCanvas(fig)
        canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        container.layout().addWidget(canvas)

        # 确保饼图容器使用所有可用空间
        container.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

    def update_card_table(self, card_amounts):
        """更新银行卡表格"""
        self.card_table.setRowCount(len(card_amounts))

        for row_idx, row in card_amounts.iterrows():
            # 卡号 (掩码显示)
            masked_card = f"{row['cardID'][:6]}****{row['cardID'][-4:]}" if row['cardID'] else "未知卡号"
            card_item = QTableWidgetItem(masked_card)
            card_item.setTextAlignment(Qt.AlignCenter)
            self.card_table.setItem(row_idx, 0, card_item)

            # 收入
            income_item = QTableWidgetItem(f"¥{row['income']:,.2f}")
            income_item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
            income_item.setForeground(QColor(SECONDARY_COLOR))
            self.card_table.setItem(row_idx, 1, income_item)

            # 支出
            expense_item = QTableWidgetItem(f"¥{row['expense']:,.2f}")
            expense_item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
            expense_item.setForeground(QColor(WARNING_COLOR))
            self.card_table.setItem(row_idx, 2, expense_item)

            # 净收入
            net_income = row['net_income']
            net_item = QTableWidgetItem(f"¥{net_income:,.2f}")
            net_item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)

            # 设置颜色
            if net_income > 0:
                net_item.setForeground(QColor(SECONDARY_COLOR))
            elif net_income < 0:
                net_item.setForeground(QColor(WARNING_COLOR))
            else:
                net_item.setForeground(QColor(TEXT_COLOR))

            self.card_table.setItem(row_idx, 3, net_item)

    def generate_chart(self, income_data, expense_data, net_data):
        """生成折线图 """
        # 清除现有图表
        layout = self.chart_frame.layout()
        while layout.count():
            widget = layout.takeAt(0).widget()
            if widget: widget.deleteLater()

        # 检查数据是否有效
        if net_data.empty:
            self.create_empty_chart()
            return

        # 创建新图表
        fig = Figure(figsize=(8, 4), dpi=100)
        ax = fig.add_subplot(111)

        try:
            # 确保索引是日期类型
            if not isinstance(net_data.index, pd.DatetimeIndex):
                net_data.index = pd.to_datetime(net_data.index)

            # 使用数值索引作为X轴
            x_values = np.arange(len(net_data))

            # 确保数据是浮点型
            net_values = net_data.values.astype(float)

            # 折线图
            ax.plot(x_values, net_values, label='每日净收入',
                    color=PRIMARY_COLOR, marker='o', linewidth=2)

            # 填充区域
            ax.fill_between(x_values, 0, net_values,
                            where=(net_values > 0),
                            interpolate=True,
                            color=SECONDARY_COLOR, alpha=0.2)

            ax.fill_between(x_values, 0, net_values,
                            where=(net_values < 0),
                            interpolate=True,
                            color=WARNING_COLOR, alpha=0.2)

            # 标记最高点和最低点
            if len(net_values) > 1:
                max_idx = net_data.idxmax()
                min_idx = net_data.idxmin()
                max_val = net_data.max()
                min_val = net_data.min()

                # 标记最大值
                if max_val > 0:
                    max_pos = list(net_data.index).index(max_idx)
                    ax.annotate(f'¥{max_val:.2f}',
                                xy=(max_pos, max_val),
                                xytext=(0, 10), textcoords='offset points',
                                arrowprops=dict(arrowstyle='->', color='black'),
                                fontsize=8)

                # 标记最小值
                if min_val < 0:
                    min_pos = list(net_data.index).index(min_idx)
                    ax.annotate(f'¥{min_val:.2f}',
                                xy=(min_pos, min_val),
                                xytext=(0, -20), textcoords='offset points',
                                arrowprops=dict(arrowstyle='->', color='black'),
                                fontsize=8)

            # 设置图表属性
            ax.set_title("月度收支趋势", fontsize=12)
            ax.set_xlabel("日期", fontsize=10)
            ax.set_ylabel("金额 (¥)", fontsize=10)
            ax.legend(loc='upper left')
            ax.grid(True, linestyle='--', alpha=0.7)


            if isinstance(net_data.index, pd.DatetimeIndex):
                dates = net_data.index.strftime("%m-%d")
            else:
                # 如果不是日期索引，使用原始索引
                dates = [str(d) for d in net_data.index]

            ax.set_xticks(x_values[::3])
            ax.set_xticklabels(dates[::3], rotation=45)

            # 自动设置Y轴范围
            max_val = max(net_values.max(), abs(net_values.min()))
            padding = max_val * 0.2 if max_val > 0 else 1000  # 20%边距或默认值

            # 设置Y轴范围
            ax.set_ylim(min(net_values.min(), 0) - padding,
                        max(net_values.max(), 0) + padding)

        except Exception as e:
            self.logger.error(f"生成图表错误: {str(e)}")
            ax.text(0.5, 0.5, "图表生成失败",
                    ha='center', va='center', fontsize=12)
            ax.axis('off')

        # 添加到UI
        canvas = FigureCanvas(fig)
        layout.addWidget(canvas)